
'use strict'

const bcrypt = require('bcrypt-promise')
// const fs = require('fs-extra')
// const mime = require('mime-types')
const sqlite = require('sqlite-async');
// const query = require('../config/connection');
const saltRounds = 10

module.exports = class User {

	constructor(dbName = 'website.db') {
		return (async() => {
			this.db = await sqlite.open(dbName)
			return this
		})()
	}

	async register(user, pass) {
		try {
			if(user.length === 0) throw new Error('missing username')
			if(pass.length === 0) throw new Error('missing password')
			let sql = `SELECT COUNT(id) as records FROM users WHERE name="${user}";`
			const data = await this.db.get(sql)
			if(data.records !== 0) throw new Error(`username "${user}" already in use`)
			pass = await bcrypt.hash(pass, saltRounds)
			sql = `INSERT INTO users(name, password, role) VALUES("${user}", "${pass}", 0)`
			await this.db.run(sql)
			return true
		} catch(err) {
			throw err
		}
	}

	// async uploadPicture(path, mimeType) {
	// 	const extension = mime.extension(mimeType)
	// 	console.log(`path: ${path}`)
	// 	console.log(`extension: ${extension}`)
	// 	//await fs.copy(path, `public/avatars/${username}.${fileExtension}`)
	// }

	async login(username, password) {
		try {
			let sql = `SELECT count(id) AS count FROM users WHERE name="${username}";`
			const records = await this.db.get(sql)
			if(!records.count) throw new Error(`username "${username}" not found`)
			sql = `SELECT id, password FROM users WHERE name = "${username}";`
			const curuser = await this.db.get(sql)
			const valid = await bcrypt.compare(password, curuser.password)
			if(valid === false) throw new Error(`invalid password for account "${username}"`)
			return curuser.id
		} catch(err) {
			throw err
		}
	}

	async getUserByName(name) {
		try {
			let sql = `SELECT * FROM users where name = ${name};`
			const records = await this.db.get(sql)
			return records
		} catch(err) {
			throw err
		}
	}

}
